// @APIVersion 1.1.0
// @Title 学生跟踪系统
// @Description 针对高校学生定制开发
package routers

import (
	"NewEdu/controllers"
	"NewEdu/utils"

	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/filter/cors"
)

func InitRouter() {
	// 初始化限流器
	utils.InitRateLimiter()

	// 全局中间件
	beego.InsertFilter("*", beego.BeforeRouter, utils.SecurityHeadersMiddleware)
	beego.InsertFilter("*", beego.BeforeRouter, utils.RateLimitMiddleware)
	beego.InsertFilter("/api/*", beego.BeforeRouter, utils.AuthMiddleware)

	// CORS配置 - 仅在dev模式下允许所有跨域访问
	if beego.BConfig.RunMode == "dev" {
		beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
			AllowOrigins:     []string{"*"},
			AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
			AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Content-Type", "X-Requested-With"},
			ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin"},
			AllowCredentials: true,
		}))
	} else {
		// 生产模式下只允许API路径跨域
		beego.InsertFilter("/api/*", beego.BeforeRouter, cors.Allow(&cors.Options{
			AllowOrigins:     []string{"*"},
			AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
			AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Content-Type"},
			ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin"},
			AllowCredentials: true,
		}))
	}

	// API路由命名空间
	ns := beego.NewNamespace("/api",
		beego.NSNamespace("/achievment",
			beego.NSInclude(
				&controllers.TAchievmentController{},
			),
		),
		beego.NSNamespace("/achievment_comments",
			beego.NSInclude(
				&controllers.TAchievmentCommentsController{},
			),
		),
		beego.NSNamespace("/depart",
			beego.NSInclude(
				&controllers.TDepartController{},
			),
		),
		beego.NSNamespace("/user",
			beego.NSInclude(
				&controllers.TUserController{},
			),
		),
		beego.NSNamespace("/user_log",
			beego.NSInclude(
				&controllers.TUserLogController{},
			),
		),
		beego.NSNamespace("/file",
			beego.NSInclude(
				&controllers.FileController{},
			),
		),
		beego.NSNamespace("/goods",
			beego.NSInclude(
				&controllers.TGoodsController{},
			),
		),
		beego.NSNamespace("/question",
			beego.NSInclude(
				&controllers.TQuestionController{},
			),
		),
		beego.NSNamespace("/answer",
			beego.NSInclude(
				&controllers.TAnswerController{},
			),
		),
		beego.NSNamespace("/records",
			beego.NSInclude(
				&controllers.RecordsController{},
			),
		),
		beego.NSNamespace("/exam",
			beego.NSInclude(
				&controllers.TExamController{},
			),
		),
		beego.NSNamespace("/examanswers",
			beego.NSInclude(
				&controllers.TExamAnswerController{},
			),
		),
	)

	// 健康检查路由
	beego.Router("/health", &controllers.HealthController{}, "get:Get")
	beego.Router("/ws/loadPersons", &controllers.RecordsController{}, "*:LoadPersons")
	// 注册命名空间
	beego.AddNamespace(ns)

	// 静态文件服务
	beego.SetStaticPath("/swagger", "swagger")
}